package com.dave.admin.modular.boss.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dave.admin.common.exception.AssertionEx;
import com.dave.admin.common.result.CommonResult;
import com.dave.admin.component.log.SysLog;
import com.dave.admin.modular.boss.entity.Role;
import com.dave.admin.modular.boss.service.IRoleService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色信息
 *
 * @author Dave
 */
@RestController
@AllArgsConstructor
@RequestMapping("/boss/role")
public class RoleController {

    private final IRoleService roleService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object list() {
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().orderByAsc(Role.CREATE_TIME));
        return CommonResult.success(roleList);
    }

    @SysLog("保存角色")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public CommonResult add(@RequestBody Role role) {
        Role targetRole = roleService.getOne(new QueryWrapper<Role>().eq(Role.NAME, role.getName()));
        AssertionEx.isNull(targetRole, "该角色已经存在，请重新输入角色名称！");
        roleService.save(role);
        return CommonResult.success(role.getId(), "添加成功");
    }

    @SysLog("通过ID更新用户")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public CommonResult update(@PathVariable String id, @RequestBody Role role) {
        role.setId(id);
        boolean pass = roleService.updateById(role);
        if (pass) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @SysLog("通过ID删除操作日志")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public CommonResult delete(@PathVariable String id) {
        Role role = roleService.getById(id);
        AssertionEx.isTrue(role != null, "该角色未找到请确认!");
        AssertionEx.isTrue(!"系统管理员".equals(role.getName()), "系统管理员角色不允许删除");
        roleService.removeById(id);
        return CommonResult.success();
    }
}
